<?php

namespace App\Service;

use App\Models\EwMember;

class MemberService extends BaseService
{
	const STATA_TRUE = 2;		//1禁用，2正常
	const STATA_FALSE = 1;		//1禁用，2正常
	const AUTH_ING = 1;			//1认证中,2通过,3拒绝
	const AUTH_PASS = 2;		//1认证中,2通过,3拒绝
	const AUTH_DENY = 3;		//1认证中,2通过,3拒绝
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否

	public static function getList($params, $count = FALSE)
	{
		$query = EwMember::query();
		$query->columns(['DISTINCT(id) AS id,nickname,bg_image,avatar,sex,sign,address,auth_state,state,is_del']);
		$query->andWhere("is_del = " . self::DEL_FALSE);

		//auth_state
		if (isset($params->auth_state) && $params->auth_state )
			$query->andwhere("auth_state =" . $params->auth_state);

		//state
		if (isset($params->state) && $params->state )
			$query->andwhere("state =" . $params->state);

		// //nickname
		// if (isset($params->nickname) && $params->nickname )
		// 	$query->andwhere("nickname LIKE '%" . $params->nickname . "%'");

		//总条数
		if ($count)
			return $query->execute()->count();

		//order_by 排序
		if (isset($params->order_by)){
			$sql = parent::orderBy($params->order_by);
			$query->orderBy($sql);
		}

		//分页
		$query->limit($params->page_num,($params->p-1)*$params->page_num);

		return $query->execute();
	}

	public static function getInfo($id = 0)
	{
		return EwMember::findFirst($id);
	}

	public static function count()
	{
		return EwMember::count();
	}

	/**
	 * [able 启用禁用]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function able($id)
	{

		if (isset($id) && $id)
			$data = EwMember::findFirst($id);

		if ($data){
			$data->state = ($data->state == 2) ? self::STATA_FALSE : self::STATA_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 移除/恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = EwMember::findFirst($id);

		if ($data){
			$data->is_del = $data->is_del ? self::DEL_FALSE : self::DEL_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 彻底删除]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwMember::findFirst($id);

		if ($row)
			return $row->delete();

		return NULL;
	}

	/**
	 * [save 保存]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{
		$row = new EwMember;
		if (isset($data->id) && $data->id)
			$row = EwMember::findFirst($data->id);

		return $row->save((array)$data);
	}
}